//
//  UIView+ZView.swift
//  swift-weibo
//
//  Created by zero on 17/3/20.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit



extension UIImage{
    
    //  屏幕截图
    class func getImageForScreen() -> UIImage?{
    
        //  获取主window
        let window = UIApplication.shared.keyWindow
        
        //  开启图片上下文
        UIGraphicsBeginImageContext(window!.bounds.size)
        
        //  把window中的渲染到图形上下文中
        window?.drawHierarchy(in: window!.bounds, afterScreenUpdates: false)
        
        //  从图形上下文中获取uiImage
        let img = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        //  关闭图形上下文
    
        return img
    }
    
    //  截取图片
    func cutImage(maxWeight:CGFloat) -> UIImage{
        
        
        if self.size.width < maxWeight {
            
            return self
        }
        
        //  计算高度
        let maxHeight = maxWeight / self.size.width * self.size.height
        
        //  得到大小
        let imageRect = CGRect(x: 0, y: 0, width: maxWeight, height: maxHeight)
        
        //  开启上下文
        UIGraphicsBeginImageContext(imageRect.size)
        
        //  把图片渲染到上下问中
        self.draw(in: imageRect)
        
        //  从上下文中获取图片
        let targetImage = UIGraphicsGetImageFromCurrentImageContext()
        //  关闭上下文
        UIGraphicsEndImageContext()
        
        return targetImage!
    }

}

extension UIButton{
    
    convenience init(title:String,fontColor:UIColor,fontSize:CGFloat,imageName:String? = nil,backImage:String? = nil){
        
        self.init()
    
        self.setTitle(title, for: .normal)
        self.setTitleColor(fontColor, for: .normal)
        self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
        
        if let image = imageName {
            self.setImage(UIImage(named:image), for: .normal)
            
        }
        
        if let back = backImage {
            
            self.setBackgroundImage(UIImage(named:back), for: .normal)
         
            self.setBackgroundImage(UIImage(named:back+"_highlighted"), for: .highlighted)
        }
        
        
        self.sizeToFit()
        
    }
}

extension UILabel{
    
    convenience init(title:String,fontColor:UIColor,fontSize:CGFloat){
        
        self.init()
        
        self.text = title
//        self.textAlignment = .center
        self.textColor = fontColor
        self.font = UIFont.systemFont(ofSize: fontSize)
        
        self.sizeToFit()
    }
}
